package com.yc.damai.biz.impl;

import com.yc.damai.entity.DmProduct;
import com.yc.damai.entity.DmPromotion;
import com.yc.damai.entity.DmPromotionDetail;
import com.yc.damai.mapper.DmProductMapper;
import com.yc.damai.mapper.DmPromotionMapper;
import com.yc.damai.biz.IDmPromotionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ly
 * @since 2024-09-28
 */
@Service
public class DmPromotionServiceImpl extends ServiceImpl<DmPromotionMapper, DmPromotion> implements IDmPromotionService {

    @Autowired
    DmPromotionMapper promotionMapper;
    @Autowired
    DmProductMapper productMapper;

    @Transactional
    @Override
    public void begin(int pmid) {
        DmPromotion dmPromotion = promotionMapper.queryById(pmid);
        for (DmPromotionDetail detail : dmPromotion.getDetails()) {
            DmProduct product = detail.getProduct();
            product.setStore(product.getStore() - detail.getNums());
            productMapper.updateById(product);
        }
        dmPromotion.setStatus(1);
        promotionMapper.updateById(dmPromotion);
    }

    @Transactional
    @Override
    public void end(DmPromotion promotion) {
        DmPromotion dmPromotion = promotionMapper.queryById(promotion.getId());
        for (DmPromotionDetail detail : dmPromotion.getDetails()) {
            DmProduct product = detail.getProduct();
            // stream 编程
            DmPromotionDetail detail1 = promotion.getDetails()
                    .stream()
                    .filter(d -> d.getId().equals(detail.getId()))
                    .collect(Collectors.toList())
                    .get(0);
            // 加上剩余的数量
            product.setStore(product.getStore() + detail1.getNums());
            productMapper.updateById(product);
        }
        dmPromotion.setStatus(2);
        promotionMapper.updateById(dmPromotion);
    }
}
